{{define "content"}}
<div x-data="roleManager()" x-init="init()">
    <!-- 页面标题 -->
    <div class="mb-6">
        <div class="flex items-center justify-between">
            <div>
                <h1 class="text-2xl font-bold text-gray-900">角色管理</h1>
                <p class="text-gray-600">管理系统角色和权限分配</p>
            </div>
            <div class="flex space-x-3">
                <a href="/system/roles/create" class="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 flex items-center">
                    <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path>
                    </svg>
                    添加角色
                </a>
                <button @click="refreshRoles()" :disabled="refreshing" class="bg-gray-600 text-white px-4 py-2 rounded-lg hover:bg-gray-700 flex items-center disabled:opacity-50 disabled:cursor-not-allowed">
                    <svg class="w-5 h-5 mr-2" :class="{'animate-spin': refreshing}" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path>
                    </svg>
                    <span x-text="refreshing ? '刷新中' : '刷新'"></span>
                </button>
            </div>
        </div>
    </div>

    <!-- 统计卡片 -->
    <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-6">
        <div class="bg-white rounded-lg shadow-sm p-6">
            <div class="flex items-center">
                <div class="flex-shrink-0">
                    <div class="w-8 h-8 bg-blue-500 rounded-md flex items-center justify-center">
                        <svg class="w-5 h-5 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z"></path>
                        </svg>
                    </div>
                </div>
                <div class="ml-4">
                    <p class="text-sm font-medium text-gray-500">总角色数</p>
                    <p class="text-2xl font-semibold text-gray-900" x-text="stats.total_roles || 0"></p>
                </div>
            </div>
        </div>
        
        <div class="bg-white rounded-lg shadow-sm p-6">
            <div class="flex items-center">
                <div class="flex-shrink-0">
                    <div class="w-8 h-8 bg-green-500 rounded-md flex items-center justify-center">
                        <svg class="w-5 h-5 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4"></path>
                        </svg>
                    </div>
                </div>
                <div class="ml-4">
                    <p class="text-sm font-medium text-gray-500">启用角色</p>
                    <p class="text-2xl font-semibold text-gray-900" x-text="stats.active_roles || 0"></p>
                </div>
            </div>
        </div>
        
        <div class="bg-white rounded-lg shadow-sm p-6">
            <div class="flex items-center">
                <div class="flex-shrink-0">
                    <div class="w-8 h-8 bg-yellow-500 rounded-md flex items-center justify-center">
                        <svg class="w-5 h-5 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 9v6m4-6v6"></path>
                        </svg>
                    </div>
                </div>
                <div class="ml-4">
                    <p class="text-sm font-medium text-gray-500">停用角色</p>
                    <p class="text-2xl font-semibold text-gray-900" x-text="stats.inactive_roles || 0"></p>
                </div>
            </div>
        </div>
        
        <div class="bg-white rounded-lg shadow-sm p-6">
            <div class="flex items-center">
                <div class="flex-shrink-0">
                    <div class="w-8 h-8 bg-purple-500 rounded-md flex items-center justify-center">
                        <svg class="w-5 h-5 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 7a2 2 0 012 2m4 0a6 6 0 01-7.743 5.743L11 17H9v2H7v2H4a1 1 0 01-1-1v-2.586a1 1 0 01.293-.707l5.964-5.964A6 6 0 1121 9z"></path>
                        </svg>
                    </div>
                </div>
                <div class="ml-4">
                    <p class="text-sm font-medium text-gray-500">权限总数</p>
                    <p class="text-2xl font-semibold text-gray-900" x-text="stats.total_permissions || 0"></p>
                </div>
            </div>
        </div>
    </div>

    <!-- 搜索和筛选 -->
    <div class="bg-white rounded-lg shadow-sm p-6 mb-6">
        <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
            <div class="flex flex-col sm:flex-row gap-4">
                <!-- 搜索框 -->
                <div class="relative">
                    <input type="text" 
                           x-model="searchQuery" 
                           @input="searchRoles()" 
                           placeholder="搜索角色名称、显示名称..." 
                           class="pl-10 pr-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 w-full sm:w-80">
                    <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                        <svg class="w-5 h-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path>
                        </svg>
                    </div>
                </div>
                
                <!-- 状态筛选 -->
                <select x-model="statusFilter" @change="filterRoles()" class="border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500">
                    <option value="">全部状态</option>
                    <option value="active">启用</option>
                    <option value="inactive">停用</option>
                </select>
            </div> 
        </div>
    </div>



    <!-- 角色列表 -->
    <div class="bg-white rounded-lg shadow-sm overflow-hidden">


        <!-- 批量操作栏 -->
        <div x-show="selectedRoles.length > 0" class="bg-blue-50 border-b border-blue-200 px-6 py-3">
            <div class="flex items-center justify-between">
                <div class="flex items-center">
                    <span class="text-sm text-blue-700">已选择 <span x-text="selectedRoles.length"></span> 个角色</span>
                </div>
                <div class="flex space-x-2">
                    <button @click="batchActivateRoles()" :disabled="selectedRoles.length === 0" class="bg-green-600 text-white px-3 py-1 rounded text-sm hover:bg-green-700 disabled:opacity-50 disabled:cursor-not-allowed">
                        批量激活
                    </button>
                    <button @click="batchDeactivateRoles()" :disabled="selectedRoles.length === 0" class="bg-yellow-600 text-white px-3 py-1 rounded text-sm hover:bg-yellow-700 disabled:opacity-50 disabled:cursor-not-allowed">
                        批量停用
                    </button>
                    <button @click="batchDeleteRoles()" :disabled="selectedRoles.length === 0" class="bg-red-600 text-white px-3 py-1 rounded text-sm hover:bg-red-700 disabled:opacity-50 disabled:cursor-not-allowed">
                        批量删除
                    </button>
                    <button @click="selectedRoles = []" class="bg-gray-600 text-white px-3 py-1 rounded text-sm hover:bg-gray-700">
                        取消选择
                    </button>
                </div>
            </div>
        </div>

        <!-- 表格头部 -->
        <div class="px-6 py-4 border-b border-gray-200">
            <div class="flex items-center justify-between">
                <h3 class="text-lg font-medium text-gray-900">角色列表</h3>
                <div class="text-sm text-gray-500">
                    共 <span x-text="pagination.total"></span> 个角色
                </div>
            </div>
        </div>
        
        
        <!-- 表格内容 -->
        <div class="overflow-x-auto">
            <!-- Loading状态 -->
            <div x-show="loading" class="flex justify-center items-center py-12">
                <div class="text-center">
                    <svg class="animate-spin w-10 h-10 text-blue-500 mb-4 mx-auto" fill="none" viewBox="0 0 24 24">
                        <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                        <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                    </svg>
                    <p class="text-gray-600">加载中...</p>
                </div>
            </div>
            
            <!-- 表格 -->
            <table x-show="!loading" class="min-w-full divide-y divide-gray-200">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            <input type="checkbox" @change="toggleSelectAll()" :checked="isAllSelected()" class="rounded border-gray-300 text-blue-600 focus:ring-blue-500">
                        </th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            角色<br>
                            信息
                        </th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            权限<br>
                            数量
                        </th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            用户<br>
                            数量
                        </th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            状态
                        </th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            创建<br>
                            时间
                        </th>
                        <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
                            操作
                        </th>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200">
                    <template x-for="role in roles" :key="role.id">
                        <tr class="hover:bg-gray-50">
                            <!-- 选择框 -->
                            <td class="px-6 py-4 whitespace-nowrap">
                                <input type="checkbox" :value="role.id" x-model="selectedRoles" class="rounded border-gray-300 text-blue-600 focus:ring-blue-500">
                            </td>
                            
                            <!-- 角色信息 -->
                            <td class="px-6 py-4 whitespace-nowrap">
                                <div class="flex items-center">
                                    <div class="flex-shrink-0 h-10 w-10">
                                        <div class="h-10 w-10 rounded-full bg-purple-500 flex items-center justify-center text-white font-medium" 
                                             x-text="role.display_name ? role.display_name.charAt(0).toUpperCase() : role.name.charAt(0).toUpperCase()"></div>
                                    </div>
                                    <div class="ml-4">
                                        <div class="text-sm font-medium text-gray-900">
                                            <a :href="'/system/roles/detail/' + role.id" class="hover:text-blue-600" x-text="role.display_name"></a>
                                        </div>
                                        <div class="text-sm text-gray-500" x-text="role.name"></div>
                                    </div>
                                </div>
                            </td>
                            
                            <!-- 权限数量 -->
                            <td class="px-6 py-4 whitespace-nowrap">
                                <div class="text-sm text-gray-900" x-text="role.permission_count || 0"></div>
                                <div class="text-sm text-gray-500">个权限</div>
                            </td>
                            
                            <!-- 用户数量 -->
                            <td class="px-6 py-4 whitespace-nowrap">
                                <div class="text-sm text-gray-900" x-text="role.user_count || 0"></div>
                                <div class="text-sm text-gray-500">个用户</div>
                            </td>
                            
                            <!-- 状态 -->
                            <td class="px-6 py-4 whitespace-nowrap">
                                <button @click="toggleRoleStatus(role)" 
                                        class="inline-flex px-2 py-1 text-xs font-semibold rounded-full cursor-pointer" 
                                        :class="role.status === 'active' ? 'bg-green-100 text-green-800 hover:bg-green-200' : 'bg-red-100 text-red-800 hover:bg-red-200'" 
                                        x-text="role.status === 'active' ? '启用' : '停用'"></button>
                            </td>
                            
                            <!-- 创建时间 -->
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                <span x-text="formatDateTime(role.created_at)"></span>
                            </td>
                            
                            <!-- 操作 -->
                            <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                                <div class="flex items-center justify-end space-x-2">
                                    <a :href="'/system/roles/detail/' + role.id" class="text-blue-600 hover:text-blue-900" title="查看详情">
                                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path>
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"></path>
                                        </svg>
                                    </a>
                                    <a :href="'/system/roles/edit/' + role.id " class="text-indigo-600 hover:text-indigo-900" title="编辑角色">
                                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"></path>
                                        </svg>
                                    </a>
                                    <button @click="manageRolePermissions(role)" class="text-purple-600 hover:text-purple-900" title="管理权限">
                                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 7a2 2 0 012 2m4 0a6 6 0 01-7.743 5.743L11 17H9v2H7v2H4a1 1 0 01-1-1v-2.586a1 1 0 01.293-.707l5.964-5.964A6 6 0 1121 9z"></path>
                                        </svg>
                                    </button>
                                    <button @click="deleteRole(role)" class="text-red-600 hover:text-red-900" title="删除角色">
                                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path>
                                        </svg>
                                    </button>
                                </div>
                            </td>
                        </tr>
                    </template>
                </tbody>
            </table>
            
            <!-- 空状态 -->
            <div x-show="!loading && roles.length === 0" class="flex flex-col items-center justify-center py-12">
                <div class="text-center">
                    <svg class="w-16 h-16 text-gray-300 mb-4 mx-auto" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z"></path>
                    </svg>
                    <h3 class="text-lg font-medium text-gray-900 mb-2">暂无角色数据</h3>
                    <p class="text-gray-500 mb-6" x-text="searchQuery || statusFilter ? '没有找到符合条件的角色，请尝试调整搜索条件' : '系统中还没有角色数据，请先创建角色'"></p>
                    <div class="flex space-x-3 justify-center">
                        <button x-show="searchQuery || statusFilter" @click="clearFilters()" class="bg-gray-600 text-white px-6 py-2 rounded-lg hover:bg-gray-700 flex items-center">
                            <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                            </svg>
                            清除筛选
                        </button>
                        <a href="/system/roles/create" class="bg-blue-600 text-white px-6 py-2 rounded-lg hover:bg-blue-700 flex items-center">
                            <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path>
                            </svg>
                            <span x-text="searchQuery || statusFilter ? '创建角色' : '创建第一个角色'"></span>
                        </a>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 分页 -->
        <div class="bg-white px-4 py-3 border-t border-gray-200 sm:px-6">
            <div class="flex items-center justify-between">
                <div class="flex-1 flex justify-between sm:hidden">
                    <button @click="previousPage()" 
                            :disabled="pagination.page <= 1"
                            class="relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 disabled:opacity-50">
                        上一页
                    </button>
                    <button @click="nextPage()" 
                            :disabled="pagination.page >= Math.ceil(pagination.total / pagination.limit)"
                            class="ml-3 relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 disabled:opacity-50">
                        下一页
                    </button>
                </div>
                <div class="hidden sm:flex-1 sm:flex sm:items-center sm:justify-between">
                    <div>
                        <p class="text-sm text-gray-700">
                            显示第 <span class="font-medium" x-text="(pagination.page - 1) * pagination.limit + 1"></span> 到 
                            <span class="font-medium" x-text="Math.min(pagination.page * pagination.limit, pagination.total)"></span> 条，
                            共 <span class="font-medium" x-text="pagination.total"></span> 条记录
                        </p>
                    </div>
                    <div>
                        <nav class="relative z-0 inline-flex rounded-md shadow-sm -space-x-px">
                            <button @click="previousPage()" 
                                    :disabled="pagination.page <= 1"
                                    class="relative inline-flex items-center px-2 py-2 rounded-l-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50 disabled:opacity-50">
                                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"></path>
                                </svg>
                            </button>
                            <template x-for="page in getPageNumbers()" :key="page">
                                <button @click="goToPage(page)" 
                                        :class="page === pagination.page ? 'bg-blue-50 border-blue-500 text-blue-600' : 'bg-white border-gray-300 text-gray-500 hover:bg-gray-50'"
                                        class="relative inline-flex items-center px-4 py-2 border text-sm font-medium" 
                                        x-text="page"></button>
                            </template>
                            <button @click="nextPage()" 
                                    :disabled="pagination.page >= Math.ceil(pagination.total / pagination.limit)"
                                    class="relative inline-flex items-center px-2 py-2 rounded-r-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50 disabled:opacity-50">
                                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"></path>
                                </svg>
                            </button>
                        </nav>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 权限管理模态框 -->
    <div x-show="showPermissionModal" 
         x-transition:enter="transition ease-out duration-300"
         x-transition:enter-start="opacity-0"
         x-transition:enter-end="opacity-100"
         x-transition:leave="transition ease-in duration-200"
         x-transition:leave-start="opacity-100"
         x-transition:leave-end="opacity-0"
         class="fixed inset-0 z-50 overflow-y-auto">
        <div class="flex items-center justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
            <div class="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity"></div>
            
            <div class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-2xl sm:w-full">
                <form @submit.prevent="updateRolePermissions()">
                    <div class="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
                        <div class="sm:flex sm:items-start">
                            <div class="w-full">
                                <h3 class="text-lg leading-6 font-medium text-gray-900 mb-4">
                                    管理角色权限 - <span x-text="permissionForm.display_name"></span>
                                </h3>
                                
                                <div class="space-y-4 max-h-96 overflow-y-auto">
                                    <template x-for="group in permissionGroups" :key="group.name">
                                        <div class="border border-gray-200 rounded-lg p-4">
                                            <h4 class="text-md font-medium text-gray-900 mb-3" x-text="group.display_name"></h4>
                                            <div class="grid grid-cols-2 gap-2">
                                                <template x-for="permission in group.permissions" :key="permission.id">
                                                    <label class="flex items-center p-2 hover:bg-gray-50 rounded">
                                                        <input type="checkbox" 
                                                               :value="permission.id" 
                                                               x-model="permissionForm.permission_ids" 
                                                               class="rounded border-gray-300 text-blue-600 focus:ring-blue-500">
                                                        <div class="ml-3">
                                                            <div class="text-sm font-medium text-gray-900" x-text="permission.display_name"></div>
                                                            <div class="text-sm text-gray-500" x-text="permission.name"></div>
                                                        </div>
                                                    </label>
                                                </template>
                                            </div>
                                        </div>
                                    </template>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
                        <button type="submit" 
                                class="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-blue-600 text-base font-medium text-white hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 sm:ml-3 sm:w-auto sm:text-sm">
                            保存
                        </button>
                        <button type="button" 
                                @click="showPermissionModal = false" 
                                class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm">
                            取消
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
function roleManager() {
    return {
        // 数据
        roles: [],
        permissions: [],
        permissionGroups: [],
        stats: {},
        selectedRoles: [],
        
        // 搜索和筛选
        searchQuery: '',
        statusFilter: '',
        
        // 加载状态
        loading: false,
        refreshing: false,
        initialized: false,
        
        // 分页
        pagination: {
            page: 1,
            limit: 10,
            total: 0
        },
        
        // 模态框状态
        showPermissionModal: false,
        
        // 表单数据
        permissionForm: {
            role_id: null,
            display_name: '',
            permission_ids: []
        },
        
        // 初始化
        async init() {
            // 防止重复初始化
            if (this.initialized || this.loading) {
                return;
            }
            this.initialized = true;
            this.loading = true;
            
            try {
                // 并行加载统计信息和角色列表，权限列表按需加载
                await Promise.all([
                    this.loadStats(),
                    this.loadRoles()
                ]);
            } catch (error) {
                console.error('初始化失败:', error);
                this.showToast('页面初始化失败', 'error');
            } finally {
                this.loading = false;
            }
        },
        
        // 加载统计信息
        async loadStats() {
            try {
                const response = await fetch('/api/v1/system/roles/stats');
                const result = await response.json();
                if (result.code === 200) {
                    this.stats = result.data;
                }
            } catch (error) {
                console.error('加载统计信息失败:', error);
            }
        },
        
        // 加载权限列表
        async loadPermissions() {
            try {
                const response = await fetch('/api/v1/system/permissions');
                const result = await response.json();
                if (result.code === 200) {
                    this.permissions = result.data.list || [];
                    this.groupPermissions();
                }
            } catch (error) {
                console.error('加载权限列表失败:', error);
            }
        },
        
        // 权限分组
        groupPermissions() {
            const groups = {};
            this.permissions.forEach(permission => {
                const groupName = permission.name.split('.')[0];
                if (!groups[groupName]) {
                    groups[groupName] = {
                        name: groupName,
                        display_name: this.getGroupDisplayName(groupName),
                        permissions: []
                    };
                }
                groups[groupName].permissions.push(permission);
            });
            this.permissionGroups = Object.values(groups);
        },
        
        // 获取权限组显示名称
        getGroupDisplayName(groupName) {
            const groupNames = {
                'user': '用户管理',
                'role': '角色管理',
                'permission': '权限管理',
                'customer': '客户管理',
                'partner': '合作伙伴',
                'push': '推送管理',
                'system': '系统管理'
            };
            return groupNames[groupName] || groupName;
        },
        
        // 加载角色列表
        async loadRoles() {
            this.loading = true;
            try {
                const params = new URLSearchParams({
                    page: this.pagination.page,
                    limit: this.pagination.limit,
                    search: this.searchQuery,
                    status: this.statusFilter
                });
                
                const response = await fetch(`/api/v1/system/roles?${params}`);
                const result = await response.json();
                
                if (result.code === 200) {
                    this.roles = result.data.list || [];
                    this.pagination.total = result.data.total || 0;
                } else if (result.message === '用户未登录') {
                    console.error('用户未登录，即将跳转到登录页面');
                    window.location.href = '/auth/login';
                } else {
                    console.error('API返回错误:', result.message);
                    this.showToast(result.message || '加载角色列表失败', 'error');
                }
            } catch (error) {
                console.error('加载角色列表失败:', error);
                this.showToast('加载角色列表失败', 'error');
            } finally {
                this.loading = false;
            }
        },
        
        // 防抖搜索定时器
        searchTimer: null,
        
        // 搜索角色
        searchRoles() {
            // 清除之前的定时器
            if (this.searchTimer) {
                clearTimeout(this.searchTimer);
            }
            
            // 设置防抖延迟
            this.searchTimer = setTimeout(() => {
                this.pagination.page = 1;
                this.loadRoles();
            }, 300);
        },
        
        // 筛选角色
        filterRoles() {
            this.pagination.page = 1;
            this.loadRoles();
        },
        
        // 清除筛选条件
        clearFilters() {
            this.searchQuery = '';
            this.statusFilter = '';
            this.pagination.page = 1;
            this.loadRoles();
        },
        
        // 刷新角色列表
        async refreshRoles() {
            this.refreshing = true;
            try {
                await Promise.all([
                    this.loadStats(),
                    this.loadRoles()
                ]);
            } finally {
                this.refreshing = false;
            }
        },
        
        // 切换角色状态
        async toggleRoleStatus(role) {
            if (confirm(`确定要${role.status === 'active' ? '停用' : '启用'}角色 ${role.display_name} 吗？`)) {
                try {
                    const response = await fetch(`/api/v1/system/roles/${role.id}/toggle-status`, {
                        method: 'POST'
                    });
                    const result = await response.json();
                    
                    if (result.code === 200) {
                         this.showToast('角色状态更新成功', 'success');
                         await Promise.all([
                             this.loadRoles(),
                             this.loadStats()
                         ]);
                     } else {
                         this.showToast(result.message, 'error');
                     }
                } catch (error) {
                    this.showToast('操作失败', 'error');
                }
            }
        },
        
        // 管理角色权限
        async manageRolePermissions(role) {
            this.permissionForm = {
                role_id: role.id,
                display_name: role.display_name,
                permission_ids: []
            };
            
            // 如果权限列表还未加载，先加载权限列表
            if (this.permissions.length === 0) {
                await this.loadPermissions();
            }
            
            // 加载角色当前权限
            try {
                const response = await fetch(`/api/v1/system/roles/${role.id}/permissions`);
                const result = await response.json();
                
                if (result.code === 200) {
                    this.permissionForm.permission_ids = (result.data || []).map(p => p.id);
                }
            } catch (error) {
                console.error('加载角色权限失败:', error);
            }
            
            this.showPermissionModal = true;
        },
        
        // 更新角色权限
        async updateRolePermissions() {
            try {
                const response = await fetch(`/api/v1/system/roles/${this.permissionForm.role_id}/permissions`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        permission_ids: this.permissionForm.permission_ids
                    })
                });
                
                const result = await response.json();
                
                if (result.code === 200) {
                    this.showToast('权限更新成功', 'success');
                    this.showPermissionModal = false;
                    await this.loadRoles();
                } else {
                    this.showToast(result.message, 'error');
                }
            } catch (error) {
                this.showToast('权限更新失败', 'error');
            }
        },
        
        // 删除角色
        async deleteRole(role) {
            if (confirm(`确定要删除角色 ${role.display_name} 吗？此操作不可恢复！`)) {
                try {
                    const response = await fetch(`/api/v1/system/roles/${role.id}`, {
                        method: 'DELETE'
                    });
                    const result = await response.json();
                    
                    if (result.code === 200) {
                         this.showToast('角色删除成功', 'success');
                         await Promise.all([
                             this.loadRoles(),
                             this.loadStats()
                         ]);
                     } else {
                         this.showToast(result.message, 'error');
                     }
                } catch (error) {
                    this.showToast('删除失败', 'error');
                }
            }
        },
        
        // 批量删除角色
        async batchDeleteRoles() {
            if (this.selectedRoles.length === 0) {
                this.showToast('请选择要删除的角色', 'warning');
                return;
            }
            
            if (confirm(`确定要删除选中的 ${this.selectedRoles.length} 个角色吗？此操作不可恢复！`)) {
                try {
                    const response = await fetch('/api/v1/system/roles/batch-delete', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            role_ids: this.selectedRoles
                        })
                    });
                    
                    const result = await response.json();
                    
                    if (result.code === 200) {
                        this.showToast('批量删除成功', 'success');
                        this.selectedRoles = [];
                        await Promise.all([
                            this.loadRoles(),
                            this.loadStats()
                        ]);
                    } else {
                        this.showToast(result.message, 'error');
                    }
                } catch (error) {
                    this.showToast('批量删除失败', 'error');
                }
            }
        },
        
        // 全选/取消全选
        toggleSelectAll() {
            if (this.isAllSelected()) {
                this.selectedRoles = [];
            } else {
                this.selectedRoles = this.roles.map(role => role.id);
            }
        },
        
        // 检查是否全选
        isAllSelected() {
            return this.roles.length > 0 && this.selectedRoles.length === this.roles.length;
        },
        
        // 分页相关
        previousPage() {
            if (this.pagination.page > 1) {
                this.pagination.page--;
                this.loadRoles();
            }
        },
        
        nextPage() {
            const maxPage = Math.ceil(this.pagination.total / this.pagination.limit);
            if (this.pagination.page < maxPage) {
                this.pagination.page++;
                this.loadRoles();
            }
        },
        
        goToPage(page) {
            this.pagination.page = page;
            this.loadRoles();
        },
        
        getPageNumbers() {
            const maxPage = Math.ceil(this.pagination.total / this.pagination.limit);
            const pages = [];
            const start = Math.max(1, this.pagination.page - 2);
            const end = Math.min(maxPage, this.pagination.page + 2);
            
            for (let i = start; i <= end; i++) {
                pages.push(i);
            }
            
            return pages;
        },
        
        // 批量操作函数
        async batchActivateRoles() {
            if (this.selectedRoles.length === 0) return;
            
            if (!confirm(`确定要激活选中的 ${this.selectedRoles.length} 个角色吗？`)) return;
            
            try {
                const response = await fetch('/api/v1/system/roles/batch-activate', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        role_ids: this.selectedRoles
                    })
                });
                
                const result = await response.json();
                
                if (result.code === 200) {
                    this.showToast('批量激活成功', 'success');
                    this.selectedRoles = [];
                    await this.loadRoles();
                } else {
                    this.showToast(result.message, 'error');
                }
            } catch (error) {
                this.showToast('批量激活失败', 'error');
            }
        },
        
        async batchDeactivateRoles() {
            if (this.selectedRoles.length === 0) return;
            
            if (!confirm(`确定要停用选中的 ${this.selectedRoles.length} 个角色吗？`)) return;
            
            try {
                const response = await fetch('/api/v1/system/roles/batch-deactivate', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        role_ids: this.selectedRoles
                    })
                });
                
                const result = await response.json();
                
                if (result.code === 200) {
                    this.showToast('批量停用成功', 'success');
                    this.selectedRoles = [];
                    await this.loadRoles();
                } else {
                    this.showToast(result.message, 'error');
                }
            } catch (error) {
                this.showToast('批量停用失败', 'error');
            }
        },
        
        // 工具函数
        formatDateTime(dateTime) {
            if (!dateTime) return '-';
            return new Date(dateTime).toLocaleString('zh-CN');
        },
        
        showToast(message, type = 'info') {
            // 这里可以集成一个 toast 组件
            console.log(`${type}: ${message}`);
            alert(message);
        }
    };
}
</script>
{{end}}